<script setup lang="ts">
import { computed, onBeforeUnmount, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { Toast } from "vant";
import type { Router } from "vue-router";
import type { Ref, ComputedRef, UnwrapNestedRefs } from "vue";
import type { LoginParams } from "@/types/userTypes/userTypes.ts";
import type { FormInstance } from "vant";
import { mobile, password, code } from "@/utils/rules.ts";
import useUserStore from "@/pinia/modules/userStore/userStore.ts";
import Tips from "@/views/login/components/Tips/Tips.vue";

const router: Router = useRouter();
const userStore = useUserStore();
const formRef = ref<FormInstance>();
const isMobileLogin: Ref<boolean> = ref<boolean>(false);
const passwordType: Ref<string|undefined> = ref<string|undefined>("password");
const loading: Ref<boolean> = ref<boolean>(false);
let timeId: any = null;
const time: Ref<number> = ref<number>(60);
const loginParams: UnwrapNestedRefs<LoginParams> = reactive<LoginParams>({
   mobile: "13230000002",
   password: "abc12345",
   code: "",
   isAgree: true,
});
const svgName: ComputedRef<string> = computed<string>(() => passwordType.value === "password" ? "eye" : "eye-open");


const changePassword = (): void => {
   passwordType.value = passwordType.value === "password" ? "text" : "password";
};

const clickLeft = (): void => {
   router.back();
};

const sendCode = async () => {
   const validateMobile = await formRef.value?.validate("mobile").catch(error => error);
   if (validateMobile) return Toast.fail(validateMobile.message);
   clearInterval(timeId);
   time.value--
   timeId = setInterval(() => {
      time.value--;
      if (time.value <= 0) {
         clearInterval(timeId);
         time.value = 60;
      }
      ;
   }, 1000);
   try {
      const response = await userStore.sendCode(loginParams.mobile, "login");
      loginParams.code = response.code;
      Toast.success(response.message);
   } catch (error: any) {
      Toast.fail(error.message);
   }
};

const handleLogin = async () => {
   if (!loginParams.isAgree) return Toast.fail("请勾选协议");
   try {
      loading.value = true;
      let result: string = "";
      if (isMobileLogin.value) {
         result = await userStore.mobileLogin({ mobile: loginParams.mobile, code: loginParams.code });
      } else {
         result = await userStore.passwordLogin({ mobile: loginParams.mobile, password: loginParams.password });
      }
      await router.push("/");
      Toast.success(result);
   } catch (error: any) {
      Toast.fail(error.message);
   } finally {
      loading.value = false;
   }
};


const handleFailed = (errorInfo: any) => {
   Toast.fail(errorInfo.errors[0].message);
};



onBeforeUnmount(()=>{
   clearInterval(timeId)
})
</script>

<template>
   <div class="login">
      <NavBar left-text="返回" left-arrow right-text="优医问诊" @click-left="clickLeft"></NavBar>
      <Tips v-model="isMobileLogin"></Tips>
      <van-form show-error :show-error-message="false" ref="formRef" @failed="handleFailed" @submit="handleLogin">
         <van-field placeholder="请输入手机号" v-model="loginParams.mobile" :rules="mobile" name="mobile"></van-field>
         <van-field placeholder="请输入密码" :type="passwordType" v-if="!isMobileLogin" v-model="loginParams.password" :rules="password" name="password">
            <template #button>
               <svg-icon :svg-name="svgName" @click="changePassword"></svg-icon>
            </template>
         </van-field>
         <van-field placeholder="请输入验证码" v-model="loginParams.code" v-else :rules="code" name="code">
            <template #button>
               <van-button size="mini" type="primary" @click="sendCode" :disabled="time<60">{{ time >= 60 ? `发送验证码` : `${time}秒后继续发送` }}</van-button>
            </template>
         </van-field>
         <div class="cell">
            <van-checkbox v-model="loginParams.isAgree"><span>我已同意</span><a>用户协议</a><span>及</span><a>隐私条款</a></van-checkbox>
         </div>
         <div class="cell">
            <van-button native-type="submit" type="primary" :loading="loading" block round>登 录</van-button>
         </div>
         <div class="cell">
            <a>忘记密码？</a>
         </div>
      </van-form>
   </div>
</template>

<style scoped lang="scss">
.login {
   .van-form {
      padding: 0 10px;

      .van-cell {
         height: 50px;
         margin: 2px 0;

         :deep(.van-field__button) {
            display: flex;
            align-items: center;
         }
      }

      .cell {
         font-size: 14px;
         height: 52px;
         line-height: 24px;
         padding: 20px 16px;
         box-sizing: border-box;
         display: flex;
         align-items: center;

         .van-checkbox {
            a {
               color: var(--cp-primary);
               padding: 0 5px;
            }
         }
      }

   }
}


</style>
